package cn.amarone.wineblog.config.security;

import cn.amarone.wineblog.models.sys.entity.SysUser;
import cn.amarone.wineblog.models.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

@Component
public class UserDetailsImpl implements UserDetailsService {

  @Autowired private IUserService userService;

  @Override
  public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
    SysUser sysUser = userService.selectByNameStateControl(username);
    if (sysUser == null) {
      throw new UsernameNotFoundException("用户信息不存在或状态异常!");
    }
    if (Integer.valueOf(1).equals(sysUser.getAble())) {
      throw new DisabledException("账号已经禁用！");
    }
    if (Integer.valueOf(2).equals(sysUser.getAble())) {
      throw new LockedException("账号已经锁定！");
    }

    return new User(
        username,
        sysUser.getPassWord(),
        AuthorityUtils.commaSeparatedStringToAuthorityList("admin"));
  }
}
